// pages/order/created_order/created_order.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    params: {},
    user_note: '',
    pricearr: {},
    goodslist: [],
    couponlist: [],
    address: '',
    addrPop: false,
    couponPop: false,
    addresslist: [],
    address_id: '',
    couponInfo: '',
    couponId: '',
    disabledBtn: false,
    totalNums: 0
  },
  orderInfoApi: function (paramsData) { //确认订单 信息
    if (this.data.disabledBtn) return;
    let params = {
      ...this.data.params
    };
    console.log(params)
    let data = Object.assign(params, paramsData || {});
    data.token = app.globalData.token;
    console.log(data);
    app.requestJs('Cart/submitorder', {
      data
    }).then((res) => {
      if (res.errcode == 1) {
        let resData = res.data || {};
        let address_id = '';
        if (resData.address) {
          data.address_id = resData.address.address_id || '';
          address_id = resData.address.address_id || '';
        }
        let total = 0
        resData.goodslist.forEach(item => {
          total += item.goods_num
        })
        this.setData({
          address: resData.address,
          couponlist: resData.couponlist,
          goodslist: resData.goodslist,
          pricearr: resData.pricearr,
          params: data,
          address_id,
          totalNums: total
        })
        console.log(this.data.params)
      } else {
        this.setData({
          address: '',
          couponlist: [],
          goodslist: [],
          pricearr: {},
          params: data,
          address_id: ''
        })
        setTimeout(() => {
          wx.showModal({
            content: res.message,
            showCancel: false
          })
        }, 500);
      }
    })
  },
  submitOrder_before: function () { //提交订单之前
    let user_note = this.data.user_note; //备注
    let data = {
      act: 'submitorder',
      user_note
    };
    this.setData({
      disabledBtn: true
    })
    this.submitOrderApi(data);
  },
  submitOrderApi: function (paramsData) { //提交订单
    let params = {
      ...this.data.params
    };
    let data = Object.assign(params, paramsData);
    data.token = app.globalData.token;
    // console.log(this.data.params);
    // return false
    app.requestJs('Cart/submitorder', {
      data
    }).then((res) => {
      // console.log(res)
      // return false
      if (res.errcode == 1) {
        app.globalData.cartUpdate = true;
        if (res.data.is_payorder) this.get_wxpayApi(res.data.ordersn);
        else {
          wx.navigateTo({ //不支付 跳转待支付
            url: '/pages/order/orderlist/orderlist?index=1',
          })
        }
      } else {
        // console.log(this.data.params);
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 5000
        })
        setTimeout(() => {
          this.setData({
            disabledBtn: false
          })
        }, 4000);
        // app.utilJs.toast({ title: res.message });
      }
    })
  },
  get_wxpayApi: function (ordersn) {
    let data = {
      token: app.globalData.token,
      ordersn
    };
    app.requestJs('Payment/getpay', {
      data
    }).then((res) => {
      if (res.errcode == 1) {
        this.order_wxPay(JSON.parse(res.data), ordersn);
      } else {
        app.utilJs.toast({
          title: res.message
        });
      }
    })
  },
  order_wxPay: function (data, ordersn) { //调起支付
    console.log(data);
    console.log(ordersn)
    wx.requestPayment({
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.package,
      signType: data.signType,
      paySign: data.paySign,
      success(res) {
        console.log(res);
        if (res.errMsg == 'requestPayment:ok') {
          setTimeout(() => {
            app.utilJs.toast({
              title: "支付成功",
              icon: 'success'
            });
          }, 200)
          // wx.redirectTo({
          //   url: '/pages/order/orderinfo/orderinfo?ordersn=' + ordersn
          // })
          wx.redirectTo({
            url: '/pages/order/orderinfo/orderinfo?ordersn=' + ordersn
          })
        }
      },
      fail(error) {
        console.log(error)
        if (error.errMsg == 'requestPayment:fail cancel') { //取消

          wx.redirectTo({
            url: '/pages/order/orderlist/orderlist?index=1&failType=1'
          })
        } else { //失败
          // app.utilJs.toast({
          //   title: error.errMsg
          // });
          app.utilJs.toast({
            title: '支付失败'
          });
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/order/orderlist/orderlist?index=0'
            })
          }, 500);
        }

      }
    })
  },
  useCoupon: function (e) { //使用优惠券
    let coupon_id = e.currentTarget.dataset.id;
    this.bindClosePop();
    this.orderInfoApi({
      coupon_id
    });
  },
  radioChange: function (e) { //选择地址
    console.log(e);
    let address_id = e.detail.value;
    this.setData({
      address_id,
    })
  },
  bindaddrPop: function () { //显示地址
    // wx.navigateTo({
    //   url: '/pages/user/address/address'
    // })
    // return
    this.setData({
      addrPop: true
    })
  },
  confirmArea: function () { //地址确定
    if (this.data.addresslist.length == 0) app.utilJs.toast({
      title: "请添加地址"
    });
    else if (this.data.address_id == '') {
      app.utilJs.toast({
        title: "请选择收货地址"
      });
    } else {
      let address_id = this.data.address_id;
      this.setData({
        addrPop: false
      })
      this.orderInfoApi({
        address_id
      });
    }
  },
  addressHandle: function (e) { //地址操作
    let that = this;
    let type = e.currentTarget.dataset.type || '';
    let id = type == '' ? '' : this.data.address_id;
    if (type == 1 && this.data.addresslist.length == 0) app.utilJs.toast({
      title: "请添加地址"
    });
    else if (type == 1 && id == '') app.utilJs.toast({
      title: "请选择需要修改的地址"
    });
    else {
      wx.navigateTo({
        url: '/pages/user/address_add/address_add?id=' + id,
        events: {
          updateData: function () {
            that.getAddress();
            that.orderInfoApi();
          },
          delUpdate: function () {
            that.getAddress();
            if (that.data.params.address_id == id) that.orderInfoApi({
              address_id: ''
            });
            else that.orderInfoApi();
          }
        }
      })
    }
  },
  bindcouponPop: function () { //优惠券显示
    this.setData({
      couponPop: true
    })
  },
  bindClosePop: function () { //关闭弹出框
    this.setData({
      addrPop: false,
      couponPop: false
    })
  },
  getAddress: function (type) { //地址列表
    let data = {
      token: app.globalData.token
    }
    app.requestJs('user/address', {
      data
    }).then((res) => {
      if (res.errcode == 1) {
        let resData = res.data || [];
        this.setData({
          addresslist: resData
        })
      } else app.utilJs.toast({
        title: res.message
      });
    })
  },
  binduser_note: function (e) { //备注
    let value = e.detail.value;
    this.setData({
      user_note: value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let goods_id = options.goods_id || '';
    let action = options.action || '';
    // 测试用
    // this.setData({
    //   address: null,
    //   pricearr: {
    //     order_amount: '39.80'
    //   },
    //   goodslist: [
    //     {
    //       id: 1,
    //       selected: false,
    //       thumb: '/img/61.png',
    //       goods_name: '海南贵妃芒果当季热带新鲜水果',
    //       specname: '100g',
    //       price: '19.90',
    //       goods_num: 1
    //     },{
    //       id: 2,
    //       selected: false,
    //       thumb: '/img/61.png',
    //       goods_name: '海南贵妃芒果当季热带新鲜水果',
    //       specname: '100g',
    //       price: '19.90',
    //       goods_num: 1
    //     }
    //   ]
    // })
    // return
    if (action == '') this.orderInfoApi({
      goods_id
    }); //购物车 
    else this.orderInfoApi(options); //立即购买
    this.getAddress();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('地址')
    this.getAddress();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})